package handler

import (
	"context"
	"gitee.com/fangy1111/shop/userop"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"userop_srv/global"
	"userop_srv/model"
)

// 留言列表
func (u UserOpServer) MessageList(ctx context.Context, request *userop.MessageRequest) (*userop.MessageListResponse, error) {
	var message []*model.LeavingMessage

	tx := global.DB.Model(&model.LeavingMessage{}).Where(model.LeavingMessage{
		UserId: request.UserId,
	}).Find(&message)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "查询列表失败")
	}
	var messageInfo []*userop.MessageResponse
	for _, v := range message {
		messageInfo = append(messageInfo, &userop.MessageResponse{
			Id:          int32(v.ID),
			UserId:      v.UserId,
			MessageType: v.MessageType,
			Subject:     v.Subject,
			Message:     v.Message,
			File:        v.File,
		})
	}

	var count int64
	tx = global.DB.Model(&model.LeavingMessage{}).Where(model.LeavingMessage{
		UserId: request.UserId,
	}).Count(&count)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "查询列表失败")
	}
	return &userop.MessageListResponse{
		Total: int32(count),
		Data:  messageInfo,
	}, nil
}

// 留言
func (u UserOpServer) CreateMessage(ctx context.Context, request *userop.MessageRequest) (*userop.MessageResponse, error) {

	message := model.LeavingMessage{
		UserId:      request.UserId,
		MessageType: request.MessageType,
		Subject:     request.Subject,
		Message:     request.Message,
		File:        request.File,
	}
	tx := global.DB.Model(&model.LeavingMessage{}).Create(&message)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "添加留言失败")
	}
	return &userop.MessageResponse{
		Id:          int32(message.ID),
		UserId:      message.UserId,
		MessageType: message.MessageType,
		Subject:     message.Subject,
		Message:     message.Message,
		File:        message.File,
	}, nil
}
